<script setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { saveComment } from "@/api/comment";

const router = useRouter();
const route = useRoute();

// 订单信息
const hotelId = route.query.hotelId;
const hotelName = route.query.hotelName;
const orderNumber = route.query.orderNumber;
const roomtypeName = route.query.roomtypeName;
const checkIn = route.query.checkIn;
const checkOut = route.query.checkOut;
const roomtypePrice = route.query.roomtypePrice;
const orderId = route.query.orderId;
const orderStatus = route.query.orderStatus;

const rating = ref(0);
const content = ref("");
const fileList = ref([]); // 已上传图片列表

//上传前检查文件大小
const beforeUpload = file => {
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) ElMessage.error("上传图片不能超过2MB");
  return isLt2M;
};

//上传成功回调（MinIO返回URL）
const handleUploadSuccess = (response, file, fileListValue) => {
  console.log("MinIO返回：", response);
  if (response.fileUrl) {
    file.url = response.fileUrl; // 让Element Plus可以预览
    ElMessage.success("图片上传成功！");
  } else {
    ElMessage.error("图片上传失败");
  }
  fileList.value = fileListValue;
};

// 删除图片
const handleRemove = (file, fileListValue) => {
  fileList.value = fileListValue;
};

// 提交评论
const submitReview = async () => {
  if (rating.value === 0) {
    ElMessage.warning("请先选择评分");
    return;
  }
  if (!content.value.trim()) {
    ElMessage.warning("请输入评论内容");
    return;
  }

  // 获取上传成功的MinIO图片URL
  const imageUrls = fileList.value.map(f => f.url);

  const commentData = {
    orderId: orderId,
    // orderNo: orderNumber,
    hotelId: hotelId,
    // hotelName: hotelName,
    rating: rating.value,
    content: content.value,
    userId: localStorage.getItem("userId") || 1,
    images: imageUrls, // 存入comment_image表
  };

  try {
    console.log("正在提交评论:", commentData);

    const res = await saveComment(commentData);
    console.log("后端返回:", res.data);

    if (res.data.code === 200) {
      ElMessage.success("评论提交成功！");
      rating.value = 0;
      content.value = "";
      fileList.value = [];
      router.push("/myComment");
    } else {
      ElMessage.error(res.data.message || "评论提交失败");
    }
  } catch (error) {
    console.error("提交评论失败:", error);
    ElMessage.error("服务器连接失败，请检查后端是否启动");
  }
};

// 点击跳转订单详情
const goOrderDetail = () => {
  router.push(`/order-detail/${orderNumber}`);
};

//点击提交评价跳转到mycomment
function toMyComment(){
  router.push(`/myComment`)
}
</script>

<template>
  <div class="review-page">
    <div class="top-nav">
      <router-link to="/">首页</router-link>
      <router-link to="/hotelDetail">酒店</router-link>
      <router-link to="/myOrder">个人中心</router-link>
    </div>

    <div class="center-wrapper">
      <div class="review-container">
        <div class="page-header">
          <h2>订单评价</h2>
        </div>

        <el-card shadow="hover" class="order-card">
          <div class="order-details">
            <h3>
              <router-link :to="`/hDetail/${hotelId}`" class="hotel-name">
                {{ hotelName }}
              </router-link>
            </h3>
            <p>
              订单编号: 
              <router-link :to="`/orderDetail/${orderId}`" class="order-no">
                {{ orderNumber }}
              </router-link>
            </p>
            <p>房型: {{ roomtypeName }}</p>
            <p>入住: {{ checkIn }} - {{ checkOut }}</p>
            <p>金额: ¥{{ roomtypePrice }} | 状态: {{ orderStatus }}</p>
          </div>
        </el-card>

        <div class="review-form">
          <h3>写下你的评论</h3>
          <div class="rating">
            <span>评分：</span>
            <el-rate v-model="rating" :allow-half="true" />
          </div>
          <el-input
            type="textarea"
            v-model="content"
            placeholder="请输入评论内容..."
            :rows="6"
          />

          <!--  调用后端MinIO接口 -->
          <el-upload
            class="upload-demo"
            action="http://localhost:8080/app/upload/uploadgeturl"
            list-type="picture-card"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :limit="5"
          >
            <i class="el-icon-plus"></i>
          </el-upload>

          <el-button type="primary" class="submit-btn" @click="submitReview()">
            提交评论
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.review-page {
  min-height: 100vh;
  background: rgba(173, 216, 230, 0.3);
  backdrop-filter: blur(15px);
  padding-bottom: 50px;
}

.top-nav {
  display: flex;
  gap: 30px;
  padding: 15px 50px;
  background: rgba(64, 158, 255, 0.7);
  color: #fff;
  font-weight: bold;
  backdrop-filter: blur(10px);
}
.top-nav a {
  color: #fff;
  text-decoration: none;
}
.top-nav a:hover {
  text-decoration: underline;
}

.center-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
}
.review-container {
  width: 900px;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 12px;
  padding: 25px;
  backdrop-filter: blur(10px);
}

.page-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 25px;
}

.order-card {
  display: flex;
  gap: 20px;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 30px;
}
.order-details {
  flex: 1;
}
.hotel-name {
  color: #409EFF;
  text-decoration: none;
}
.hotel-name:hover {
  text-decoration: underline;
}
.order-details h3 {
  margin: 0 0 8px 0;
  font-size: 22px;
}
.order-details p {
  margin: 4px 0;
  color: #666;
}
.order-no {
  color: #409EFF;
  cursor: pointer;
}
.order-no:hover {
  text-decoration: underline;
}

.review-form h3 {
  margin-bottom: 15px;
  font-size: 20px;
  color: #333;
}
.rating {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

/* 调整上传图片显示高度 */
.upload-demo {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}
.upload-demo ::v-deep(.el-upload-list__item) {
  width: 100px !important;
  height: 100px !important;
}
.upload-demo ::v-deep(.el-upload-list__item img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.submit-btn {
  margin-top: 15px;
}
</style>
